package emailUtil;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author : yangfan
 * @DATE : 2016/11/5
 * @TIME : 12:22
 * @VERSION : 1.0
 * @DESC : 邮箱相关的操作,用到的jar包:mail.jar
 */
public class EmailUtil {
    public static void sendEmail(EmailInfo emailInfo) {
        Properties properties = new Properties();
        InputStream in = Object.class.getResourceAsStream("/mail.properties");
        String firstname;
        try {
            properties.load(in);
            //判断服务器类型
        } catch (IOException e) {
            System.out.println("配置文件读取出错");
            e.printStackTrace();
        }
        Session mailSession = Session.getDefaultInstance(properties);
        mailSession.setDebug(true);
        MimeMessage message = new MimeMessage(mailSession);
        Transport transport = null;
        try {
            message.setFrom(new InternetAddress(properties.getProperty("mail.smtps.from")));
            message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(emailInfo.getReceiveAddress()));
            message.setSubject(emailInfo.getSubject());
            message.setText(emailInfo.getContext());
            transport = mailSession.getTransport();
            transport.connect(properties.getProperty("mail.smtps.host"), Integer.parseInt(properties.getProperty("mail.smtp.port")), properties.getProperty("mail.smtps.user"), properties.getProperty("mail.smtps.password"));
            transport.sendMessage(message, message.getAllRecipients());
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
}